﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yipusoft.Common.BLL;
using Yipusoft.Account.BLL;
using Yipusoft.Account.Model;
using Yipusoft.SoldierArchives.Model;
using Yipusoft.SoldierArchives.BLL;
using System.Drawing;
using System.IO;
using Yipusoft.Common.Model;

public partial class Police_TranslateDocument_NewSoldier : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindNation();
            BindDuty();
            BindRank();
            BindSpeciality();
            BindProvince();
            BindBackground();
            BindCulture();
            BindReligion();
            BindStatus();
            BindCities(ddlProvinces.SelectedValue);
            BindSpeciality(ddlSpeciality1.SelectedValue);
            if (String.IsNullOrEmpty(Request["ID"]))
                BindDepartment("203001", "203002", "203003");
            else
                BindDepartment("203001", "203004", "203005");
            InitDate();
        }
    }

    private void InitDate()
    {
        if (Request.QueryString["Fid"] != null)
        {
            TranslateInfo info = Translate.GetDetail(new Guid(Request.QueryString["Fid"].ToString()));
            SoldierName.Text = info.SoldierName;
            ddlSex.SelectedItem.Text = info.Sex;
            JoinDate.Text = info.DateArmy.ToShortDateString();

        }
    }

    private void BindNation()
    {
        ListItem blankLI = new ListItem("", "");
        ddlNation.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='MZ00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlNation.Items.Add(li);
        }
    }

    private void BindDuty()
    {

        ListItem blankLI = new ListItem("", "");
        ddlDuty.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='SBZW00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlDuty.Items.Add(li);
        }
    }

    private void BindRank()
    {

        ListItem blankLI = new ListItem("", "");
        ddlRank.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='SBJX00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlRank.Items.Add(li);
        }
    }

    private void BindSpeciality()
    {

        ListItem blankLI = new ListItem("", "");
        ddlSpeciality1.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='ZY0000' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlSpeciality1.Items.Add(li);
        }
    }

    private void BindProvince()
    {

        ListItem blankLI = new ListItem("", "");
        ddlProvinces.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='SS000000' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlProvinces.Items.Add(li);
        }
    }

    private void BindBackground()
    {

        ListItem blankLI = new ListItem("", "");
        ddlBackground.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='JTCS00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlBackground.Items.Add(li);
        }
    }

    private void BindStatus()
    {

        ListItem blankLI = new ListItem("", "");
        ddlStatus.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='SBBRCF00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlStatus.Items.Add(li);
        }
    }

    private void BindCulture()
    {

        ListItem blankLI = new ListItem("", "");
        ddlCulture.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='WHCD00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlCulture.Items.Add(li);
        }
    }

    private void BindReligion()
    {

        ListItem blankLI = new ListItem("", "");
        ddlReligion.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='ZJXY00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlReligion.Items.Add(li);
        }
    }
    protected void ddlProvinces_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindCities(ddlProvinces.SelectedValue);
    }

    private void BindCities(string province)
    {

        ddlCities.Items.Clear();
        if (province.Trim() == "")
        {
            ListItem blankLI = new ListItem("", "");
            ddlCities.Items.Add(blankLI);
        }
        else
        {
            foreach (CodeItemInfo item in CodeItem.GetList("ParentID='" + province + "' Order by SeqID"))
            {
                ListItem li = new ListItem(item.ItemName, item.ItemID);
                ddlCities.Items.Add(li);
                foreach (CodeItemInfo subItem in CodeItem.GetList("ParentID='" + item.ItemID + "' Order by SeqID"))
                    ddlCities.Items.Add(new ListItem("\u3000" + subItem.ItemName, subItem.ItemID));
            }
        }
    }
    protected void ddlSpeciality1_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindSpeciality(ddlSpeciality1.SelectedValue);
    }

    private void BindSpeciality(string speciality)
    {
        ddlSpeciality2.Items.Clear();
        if (speciality.Trim() == "")
        {
            ListItem blankLI = new ListItem("", "");
            ddlSpeciality2.Items.Add(blankLI);
        }
        else
        {
            ddlSpeciality2.DataSource = CodeItem.GetList("ParentID='" + speciality + "' Order by SeqID");
            ddlSpeciality2.DataTextField = "ItemName";
            ddlSpeciality2.DataValueField = "ItemID";
            ddlSpeciality2.DataBind();
        }
    }

    private void BindDepartment(string permissionAdmin, string permissionLevel, string permissionUnit)
    {
        ddlDepartment.DataSource = GetDepartmentList(Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID, permissionAdmin, permissionLevel, permissionUnit);
        ddlDepartment.DataTextField = "FullName";
        ddlDepartment.DataValueField = "DepartmentID";
        ddlDepartment.DataBind();
    }

    private List<DepartmentInfo> GetDepartmentList(string departmentID, string permissionAdmin, string permissionLevel, string permissionUnit)
    {
        List<DepartmentInfo> departmentList = new List<DepartmentInfo>();
        if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionAdmin))
            departmentList = Department.GetList("1=1");
        else

            if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionLevel))
                departmentList = Department.GetList("DepartmentID like '" + departmentID.Substring(0, 4) + "%'");
            else
                if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionUnit))
                    departmentList = Department.GetList("DepartmentID='" + departmentID + "'");

        return departmentList;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string photo = UploadPhoto(200, 250);
        if (photo == "%")
        {
            lblInfo.ForeColor = Color.Red;
            lblInfo.Text = "上传照片不支持此文件类型!";
            return;
        }
        if (photo == "-")
        {
            lblInfo.ForeColor = Color.Red;
            lblInfo.Text = "超过允许的图片尺寸(200×250)范围!";
            return;
        }
        if (photo == "#")
        {
            lblInfo.ForeColor = Color.Red;
            lblInfo.Text = "上传文件出错!";
            return;
        }
        if (ddlDepartment.SelectedValue == "")
        {
            lblInfo.ForeColor = Color.Red;
            lblInfo.Text = "对不起,部门不能为空!";
            return;
        }
        SoldierArchiveInfo soldierInfo = new SoldierArchiveInfo();
        soldierInfo.Picture = photo;
        AssignSoldierInfo(soldierInfo);
        Soldier soldier = new Soldier();
        Guid Sid=soldier.Insert2(soldierInfo, User.Identity.Name, Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName);
        if(Sid!=Guid.Empty)
        {
            EventLogInfo log = new EventLogInfo();
            log.EventTime = DateTime.Now;
            log.EventType = 1;
            log.EventData = "添加新士兵";
            log.ItemID = soldierInfo.SoldierName;
            log.ItemName = "BasicBase";
            log.ItemFullUrl = "SoldierArchive/NewSoldier.aspx";
            log.CreatedBy = Context.User.Identity.Name;
            log.CreatedTime = DateTime.Now;
            log.UserIP = Request.UserHostAddress;
            EventLog.Insert(log);

            TranslateInfo info = Translate.GetDetail(new Guid(Request.QueryString["Fid"].ToString()));
            info.SID = Sid;
            Translate.Update(info);
            //写入流程
            TranslateLogInfo Tlog = new TranslateLogInfo();
            Tlog.DID = Guid.Empty;
            Tlog.FID = new Guid(Request["Fid"]);
            Tlog.LastTime = DateTime.Now;
            Tlog.PID = TranslateProcess.GetNextDetail(TranslateLogs.GetLastDetail(info.ID).PID).ID;
            TranslateLogs.Insert(Tlog);

            lblInfo.ForeColor = Color.Black;
            lblInfo.Text = "保存成功";
            Response.Redirect("TransLateDepartment.aspx?Fid=" + Request["Fid"]);
        }
        else
        {
            lblInfo.ForeColor = Color.Red;
            lblInfo.Text = "保存失败！";
        }
    }

    private void AssignSoldierInfo(SoldierArchiveInfo soldierInfo)
    {
        soldierInfo.Background = ddlBackground.SelectedValue;
        soldierInfo.Birthday = Birthday.Text == "" ? DateTime.MinValue : Convert.ToDateTime(Birthday.Text);
        soldierInfo.CardID = CardID.Text;
        soldierInfo.ChooseID = ChooseID.Text;
        soldierInfo.ConfirmID = ConfirmID.Text;
        soldierInfo.Culture = ddlCulture.SelectedValue;
        soldierInfo.DepartmentID = ddlDepartment.SelectedValue;
        soldierInfo.Duty = ddlDuty.SelectedValue;
        soldierInfo.Height = Height.Text == "" ? 0 : int.Parse(Height.Text);
        soldierInfo.HomePlace = HomePlace.Text;
        soldierInfo.JoinPlace = JoinPlace.Text;
        soldierInfo.JoinTime = JoinDate.Text == "" ? DateTime.MinValue : Convert.ToDateTime(JoinDate.Text);
        soldierInfo.Marriage = ddlMerriage.SelectedValue;
        soldierInfo.Nation = ddlNation.SelectedValue;
        soldierInfo.Native = ddlCities.SelectedValue;
        soldierInfo.PartyTime = PartyDate.Text == "" ? DateTime.MinValue : Convert.ToDateTime(PartyDate.Text);
        soldierInfo.Rank = ddlRank.SelectedValue;
        soldierInfo.RegisterID = RegisterID.Text;
        soldierInfo.Religion = ddlReligion.SelectedValue;
        soldierInfo.Sex = ddlSex.SelectedValue;
        soldierInfo.SoldierName = SoldierName.Text;
        soldierInfo.Speciality1 = ddlSpeciality1.SelectedValue;
        soldierInfo.Speciality2 = ddlSpeciality2.SelectedValue;
        soldierInfo.Status = ddlStatus.SelectedValue;
        soldierInfo.Weight = Weight.Text == "" ? 0 : Convert.ToDecimal(Weight.Text);
        soldierInfo.YouthTime = YouthDate.Text == "" ? DateTime.MinValue : Convert.ToDateTime(YouthDate.Text);
        soldierInfo.IsContract = IsContract.Checked;
    }

    /// <summary>
    /// 上传头像
    /// </summary>
    /// <param name="limitWidth"></param>
    /// <param name="limitHeight"></param>
    /// <returns>
    /// %：不支持的上传文件类型
    /// -：超过规定的尺寸
    /// #：上传文件出错
    /// </returns>
    private string UploadPhoto(int limitWidth, int limitHeight)
    {
        string ret = "";
        if (fileUpload.PostedFile != null && fileUpload.PostedFile.ContentLength > 0)
        {
            try
            {
                // if not already present, create a directory named /Uploads/<CurrentUserName>
                string filename = fileUpload.FileName.ToLower();
                int i = filename.LastIndexOf(".");
                filename = filename.Substring(i, filename.Length - i);

                if (!(filename == ".jpg" || filename == ".jpeg" || filename == ".gif" || filename == ".png" || filename == ".bmp"))
                {
                    ret = "%";

                }//检查上传文件的格式是否有效
                else
                {
                    Stream oStream = fileUpload.PostedFile.InputStream;
                    System.Drawing.Image oImage = System.Drawing.Image.FromStream(oStream);

                    int owidth = oImage.Width; //原图宽度
                    int oheight = oImage.Height; //原图高度

                    if (owidth > limitWidth || oheight > limitHeight)
                    {
                        ret = "-";

                    }//检查是否超出规定尺寸
                    else
                    {
                        string dirUrl = this.Request.ApplicationPath +
                           "/Uploads/" + this.Page.User.Identity.Name;
                        string dirPath = Server.MapPath(dirUrl);
                        if (!Directory.Exists(dirPath))
                            Directory.CreateDirectory(dirPath);
                        // save the file under the user's personal folder
                        string fileUrl = dirUrl + "/" + DateTime.Now.ToString("yyMMddHHmmss") + filename;
                        fileUpload.PostedFile.SaveAs(Server.MapPath(fileUrl));
                        //Profile.Initialize(this.Page.User.Identity.Name, true);
                        ret = fileUrl;
                    }
                }
            }
            catch
            {
                ret = "#";
            }
        }
        return ret;
    }


    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        string photo = UploadPhoto(200, 250);
        if (photo == "%")
        {
            lblInfo.ForeColor = Color.Red;
            lblInfo.Text = "上传照片不支持此文件类型!";
            return;
        }
        if (photo == "-")
        {
            lblInfo.ForeColor = Color.Red;
            lblInfo.Text = "超过允许的图片尺寸(200×250)范围!";
            return;
        }
        if (photo == "#")
        {
            lblInfo.ForeColor = Color.Red;
            lblInfo.Text = "上传文件出错!";
            return;
        }
        if (ddlDepartment.SelectedValue == "")
        {
            lblInfo.ForeColor = Color.Red;
            lblInfo.Text = "对不起,部门不能为空!";
            return;
        }
        Soldier soldier = new Soldier();
        SoldierArchiveInfo soldierInfo = soldier.GetSoldierInfoByID(Request["ID"]);
        if (photo != "")
            soldierInfo.Picture = photo;
        AssignSoldierInfo(soldierInfo);
        if (soldier.Update(soldierInfo, User.Identity.Name, Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName))
        {
            EventLogInfo log = new EventLogInfo();
            log.EventTime = DateTime.Now;
            log.EventType = 1;
            log.EventData = "修改了一个士兵";
            log.ItemID = soldierInfo.SoldierName;
            log.ItemName = "BasicBase";
            log.ItemFullUrl = "SoldierArchive/NewSoldier.aspx";
            log.CreatedBy = Context.User.Identity.Name;
            log.CreatedTime = DateTime.Now;
            log.UserIP = Request.UserHostAddress;
            EventLog.Insert(log);
            lblInfo.ForeColor = Color.Black;
            lblInfo.Text = "保存成功。";
            InitDate();
        }
        else
        {
            lblInfo.ForeColor = Color.Red;
            lblInfo.Text = "保存失败！";
        }

    }


    protected void btnAutoWrite_Click(object sender, EventArgs e)
    {
        CardCodeInfo cardCodeInfo = CardCode.GetCardCodeInfoByDepartmentID(ddlDepartment.SelectedValue.Substring(0, 4) + "000");
        if (cardCodeInfo != null)
        {
            int len = cardCodeInfo.StartNum.Length;
            Soldier soldier = new Soldier();
            for (int i = int.Parse(cardCodeInfo.StartNum); i <= int.Parse(cardCodeInfo.EndNum); i++)
            {
                string cardID = cardCodeInfo.FrontCode + i.ToString().PadLeft(len, '0');
                if (soldier.GetSoldiersCountByWhere("CardID='" + cardID + "' and Left(DepartmentID,4)='" + cardCodeInfo.DepartmentID.Substring(0, 4) + "'") == 0)
                {
                    CardID.Text = cardID;
                    break;
                }

            }
        }
        else
            CardID.Text = "";
    }
}
